package com.qf.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.cache.RedisUtil;
import com.qf.commons.JwtUtil;
import com.qf.commons.PhoneCodeUtil;
import com.qf.entity.Collect;
import com.qf.entity.Hotal;
import com.qf.entity.R;
import com.qf.entity.User;
import com.qf.feign.HotalFeign;
import com.qf.service.CollectService;
import com.qf.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;


/**
 * (User)表控制层
 *
 * @author makejava
 * @since 2020-10-01 21:49:38
 */
@RestController
@RequestMapping("user")
public class UserController{
    /**
     * 服务对象
     */
    @Autowired
    private UserService userService;
    @Autowired
    private HotalFeign hotalFeign;
    @Value("${spring.mail.username}")
    private String sendName;
    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    private CollectService collectService;
    @Autowired
    private RedisUtil redisUtil;

    @RequestMapping("/register")
    public R<Boolean> register(User user,String code){
        boolean flag = true;

        String veryCode = (String) redisUtil.getCache(user.getEmail());
        System.out.println("code:"+code);
        System.out.println("veryCode:"+veryCode);
        try {
            if (code.equals(veryCode)){
                userService.save(user);
                List<Hotal> list = hotalFeign.list().getData();
                for (int i = 1;i<list.size();i++){
                    Collect collect = new Collect()
                            .setUserId(user.getId())
                            .setDate(new Date())
                            .setCode(0)
                            .setHid(list.get(i).getId());
                    collectService.save(collect);
                }
                return new R<Boolean>().setCode(R.Code.SUCCESS).setMsg("注册成功").setData(flag);
            }else{
                return new R<Boolean>().setCode(R.Code.ERROR).setMsg("请重新输入").setData(false);
            }
        }catch (Exception e){
            return new R<Boolean>().setCode(R.Code.ERROR).setMsg("用户名已存在").setData(flag);
        }
    }
    @RequestMapping("/login")
    public R<String> login(String username,String password,String devid){
        User user = userService.getOne(new QueryWrapper<User>().eq("username", username).eq("password", password));
        if(user != null){
            String token = JwtUtil.createToken(user, devid);
            return new R<String>().setData(token);
        }
        return new R<String>().setCode(R.Code.ERROR).setMsg("账号或者密码错误");
    }

    @RequestMapping("/forget")
    public R<Boolean> forget(User user,String code){
        boolean flag = true;
        User user1 = userService.getOne(new QueryWrapper<User>().eq("username", user.getUsername()));
        String veryCode = (String) redisUtil.getCache(user.getEmail());
        System.out.println("code:"+code);
        System.out.println("veryCode:"+veryCode);
        try {
            if (code.equals(veryCode)){
                userService.update(new QueryWrapper<User>().eq("username",user1.getUsername()));
                return new R<Boolean>().setCode(R.Code.SUCCESS).setMsg("修改成功").setData(flag);
            }else{
                return new R<Boolean>().setCode(R.Code.ERROR).setMsg("验证码错误").setData(false);
            }
        }catch (Exception e){
            return new R<Boolean>().setCode(R.Code.ERROR).setMsg("用户名不存在").setData(flag);
        }
    }

    @RequestMapping("/sendEmail")
    public R<String> sendEmail(String email,String ActionType,String username){
        if (ActionType == ""){
            //设置验证码位数，随机生成6位
            String msg = PhoneCodeUtil.generateVerifyCode(6);

            redisUtil.setCache(email,msg);

            if (StringUtils.isEmpty(msg) || StringUtils.isEmpty(email)){
                return new R<String>().setData("请输入邮箱");
            }
            try{
                SimpleMailMessage mail = new SimpleMailMessage();
                mail.setFrom(sendName);
                mail.setTo(email);
                mail.setSubject("这是一个简单的邮件");
                mail.setText(msg);
                mailSender.send(mail);
                return new R<String>().setData(msg);
            }catch (Exception e){
                e.printStackTrace();
                return new R<String>().setData("服务繁忙");
            }
        }else {
            User user = userService.getOne(new QueryWrapper<User>().eq("username", username));
            String email1 = user.getEmail();
            String msg = PhoneCodeUtil.generateVerifyCode(6);
            redisUtil.setCache(email,msg);
            try{
                SimpleMailMessage mail = new SimpleMailMessage();
                mail.setFrom(sendName);
                mail.setTo(email1);
                mail.setSubject("这是一个简单的邮件");
                mail.setText(msg);
                mailSender.send(mail);
                return new R<String>().setData(msg);
            }catch (Exception e){
                e.printStackTrace();
                return new R<String>().setData("服务繁忙");
            }
        }
    }
    /*@RequestMapping("/acEmail")
    public R<String> acEmail(String email){
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper messageHelper;

        String cache = (String) ehcacheUtil.getCache(eKey);

        String code = (String) redisUtil.getCache(cache);

        String context = "<a href=\"http://localhost:8085/user/checkCode?email="+email+"\">激活请点击:"+code+"</a>";
        try {
            messageHelper = new MimeMessageHelper(message, true);
            //邮件发送人
            messageHelper.setFrom(sendName);
            //邮件接收人
            messageHelper.setTo(email);
            //邮件主题
            message.setSubject("这是一封激活邮件");
            //邮件内容，html格式
            messageHelper.setText(context, true);
            //发送
            mailSender.send(message);
            return new R<String>().setData(context);
        } catch (MessagingException e) {
            e.printStackTrace();
            return new R<String>().setData("服务繁忙");
        }
    }
    @GetMapping("/checkCode")
    public String checkCode(String code){
        String cache = (String) ehcacheUtil.getCache(eKey);

        String code1 = (String) redisUtil.getCache(cache);
        //如果用户不等于null，把用户状态修改status=1
        if (code1.equals(code)){
            userService.getById()
        }
        return "login";
    }*/


}